﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Windows.Forms;
namespace QUANLIHOCSINH.DataAccess
{
    class ConnectData
    {
        // private string strConnection = "Server=ThaiChau-PC;Database=QuanLiHocSinh;User Id=sa;Password=1234567";
        private SqlConnection conn;
        private SqlDataAdapter dataAp;
        private DataTable datatable;
        public ConnectData()
        {
            Connect();
        }
        // Ket noi
        public void Connect()
        {
            string strConnection = "Server=MICROSOF-89AF53;Database=QuanLiHocSinh;Integrated Security = True";
            try
            {
                this.conn = new SqlConnection(strConnection);
                this.conn.Open();
                this.conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lo" + ex.Message);
            }
        }
        public DataTable GetData(string sql)
        {
            this.Connect();

            dataAp = new SqlDataAdapter(sql, conn);
            datatable = new DataTable();
            dataAp.Fill(datatable);
            return datatable;
        }
        public bool ExecuteQuery(string sql)
        {
            int numRecordsEffect = 0;
            try
            {
                if (conn.State == ConnectionState.Closed)
                    conn.Open();
                SqlCommand cmd = new SqlCommand(sql, conn);
                numRecordsEffect = cmd.ExecuteNonQuery();
                if (conn.State == ConnectionState.Open)
                    conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi: " + ex.Message);
            }
            if (numRecordsEffect > 0)
                return true;
            return false;
        }
        public string GetLastID(string nameTable, string nameField)
        {
            string sql = "select top 1" + nameField + " From " + nameTable + " ORDER BY " + nameField + " DESC";
            GetData(sql);
            if (GetData(sql).Rows.Count > 0)
            {
                return datatable.Rows[0][nameField].ToString();
            }
            else
            {
                return "";
            }
        }
    }
}
